package com.yinhe.music.yhmusic.manager;

import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusListObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.adapter.MusicManagerAdapter;
import com.yinhe.music.yhmusic.base.BaseModel;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.BaseServiceActivity;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.db.DataBaseAccessor;
import com.yinhe.music.yhmusic.db.bean.RecentMusicDBEntity;
import com.yinhe.music.yhmusic.dialog.DeleteDialog;
import com.yinhe.music.yhmusic.dialog.DownloadDialog;
import com.yinhe.music.yhmusic.dialog.NetProtectDialog;
import com.yinhe.music.yhmusic.dialog.collect.CollectionDialog;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.utils.DataHolder;
import com.yinhe.music.yhmusic.utils.NetworkUtils;
import com.yinhe.music.yhmusic.utils.Preferences;
import com.yinhe.music.yhmusic.utils.ToastUtils;
import com.yinhe.music.yhmusic.widget.WrapContentLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.yinhe.music.yhmusic.constants.IConstants.RECENT_PLAY_MANAGER;

/**
 *
 */
public class ManageActivity extends BaseServiceActivity implements IMusicManagerContract.IMusicManagerView {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.play)
    TextView play;
    @BindView(R.id.add_to)
    TextView addTo;
    @BindView(R.id.down)
    TextView down;
    @BindView(R.id.delete)
    TextView delete;
    @BindView(R.id.bottom_menu)
    FrameLayout bottomMenu;

    private int managerType;
    private boolean isSelect = false;
    private List<Music> mList = new ArrayList<>();
    private MusicManagerAdapter managerAdapter;
    private Enum type;
    private int menuId;

    MusicManagerPresenter mPresenter;

    @Override
    public void initView() {
        RxBus.get().register(this);

        if (getIntent() != null) {
            managerType = getIntent().getIntExtra("manager_type", -1);
            type = (Enum) getIntent().getSerializableExtra("type");
            menuId = getIntent().getIntExtra("menuid", 0);
        }

        showQuickControl(false);

        if (managerType == RECENT_PLAY_MANAGER) {
            List<RecentMusicDBEntity> recentList = DataBaseAccessor.getInstance().getAllRecent();
            if (recentList == null) {
                return;
            }

            for (RecentMusicDBEntity recentMusicDBEntity : recentList) {
                mList.add(new Music(recentMusicDBEntity));
            }
        } else {
            mList = DataHolder.getInstance().getData();
        }
        setToolbar("批量操作");
        setBottom();
        setList();
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_manage;
    }

    @Override
    public BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void initPresenter() {
        mPresenter = new MusicManagerPresenter();
        mPresenter.attachModelView(new BaseModel(), this);
    }

    @Override
    public void onDestroy() {
        RxBus.get().unregister(this);
        updateSelect(false);
        super.onDestroy();
    }

    private void setList() {
        managerAdapter = new MusicManagerAdapter(mList);
        updateSelect(false);
        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this));
        recyclerView.setAdapter(managerAdapter);
        recyclerView.setHasFixedSize(true);
    }

    private void setBottom() {
        if (type == Music.Type.ONLINE) {
            delete.setVisibility(View.GONE);
        } else if (type == Music.Type.LOCAL || managerType == IConstants.DOWN_FINISH_MANAGER) {
            down.setVisibility(View.GONE);
        }

        NetProtectDialog dialog = new NetProtectDialog(ManageActivity.this, () -> {
            mPresenter.getBatchDownId(mList);
        });

        play.setOnClickListener(view -> {
            List<Music> musicList = new ArrayList<>();
            for (Music i : mList) {
                if (i.isChecked()) {
                    musicList.add(i);
                }
            }
            if (mService != null) {
                mService.addMusicListToPlayList(musicList, mService.getPlayingPosition());
            }
        });

        addTo.setOnClickListener(view -> {
            ArrayList<Integer> idList = new ArrayList<>();
            for (Music i : mList) {
                if (i.isChecked()) {
                    idList.add((int) i.getSongId());
                }
            }

            if (idList.isEmpty()) {
                ToastUtils.show("请选择要添加的歌曲");
                return;
            }
            CollectionDialog.newInstance(idList, IConstants.ONLINE).show(
                    getSupportFragmentManager(), "CollectionDialog");
        });

        down.setOnClickListener(v -> {
            if (Preferences.getLoginSn().isEmpty()) {
                startLogin();
                return;
            }
            if (!NetworkUtils.isConnectWifi(ManageActivity.this) && Preferences.getIsProtect()) {
                dialog.show();
            } else {
                mPresenter.getBatchDownId(mList);
            }
        });

        delete.setOnClickListener(view -> {
            if (mList != null) {
                mPresenter.getDeleteList(mList);
            }
        });
    }

    @Override
    public void showDownTips(List<Music> downList) {
        DownloadDialog dialog = new DownloadDialog(this, downList.size(),
                () -> mPresenter.reqDownMusic(downList, null, mService));
        dialog.show();
    }

    @Override
    public void showDeleteDialog(List<Integer> deleteIdList) {
        DeleteDialog dialog = new DeleteDialog(this, deleteIdList, (hasDownList, deleteFile) ->
                mPresenter.deleteMusic(deleteIdList, hasDownList, menuId, managerType, deleteFile));
        dialog.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_select, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_all) {
            if (isSelect) {
                isSelect = false;
                item.setTitle("全选");
                updateSelect(false);
            } else {
                item.setTitle("取消全选");
                isSelect = true;
                updateSelect(true);
            }
        }
        return super.onOptionsItemSelected(item);
    }

    private void updateSelect(boolean select) {
        for (int i = 0; i < mList.size(); i++) {
            mList.get(i).setChecked(select);
        }
        managerAdapter.notifyDataSetChanged();
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.SongMenu.DELETE_MENU_LOCAL_MUSIC)
    )
    public void onRxbusDeleteMenuLocalMusic(Integer songId) {
        List<Music> mList = managerAdapter.getData();
        for (Music i : managerAdapter.getData()) {
            if (i.getSongId() == songId) {
                mList.remove(i);
            }
        }
        managerAdapter.notifyDataSetChanged();
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.SongMenu.DELETE_MENU_MUSIC)
    )
    public void onRxbusDeleteMenuMusic(RxbusListObject rxbusListObject) {
        if (rxbusListObject.rxList == null) {
            return;
        }
        List<Integer> idList = (List<Integer>) rxbusListObject.rxList;
        List<Music> deleteList = new ArrayList<>();
        for (Music i : mList) {
            for (int j : idList) {
                if (i.getSongId() == j) {
                    deleteList.add(i);
                }
            }
        }
        mList.removeAll(deleteList);
        managerAdapter.notifyDataSetChanged();
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.Music.DELETE_DOWN_MUSIC),
                    @Tag(RxBusEventType.Recent.DELETE_RECENT_MUSIC)}
    )
    public void onRxbusDeleteDownMusic(RxbusListObject rxbusListObject) {
        List<Music> deleteList = new ArrayList<>();
        if (rxbusListObject != null) {
            for (Music i : mList) {
                for (Object j : rxbusListObject.rxList) {
                    if (i.getSongId() == (Integer) j) {
                        deleteList.add(i);
                    }
                }
            }
            mList.removeAll(deleteList);
        }
        managerAdapter.notifyDataSetChanged();
    }
}
